/**    
 * @{#} SearchQuestionActivity.java Create on 2014-6-10 下午1:35:57    
 *          
 * @author <a href="mailto:evan0502@qq.com">Evan</a>   
 * @version 1.0    
 */
package com.smiier.skin;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import cn.o.app.util.OUtil;
import cn.skinapp.R;

import com.evan.common.handler.RequestHandler;
import com.evan.common.handler.callback.HandlerCallback;
import com.evan.common.pullrefresh.PullToRefreshBase;
import com.evan.common.pullrefresh.PullToRefreshBase.OnRefreshListener;
import com.evan.common.pullrefresh.PullToRefreshListView;
import com.smiier.skin.adapter.QuestionAdapter;
import com.smiier.skin.constant.Constant;
import com.smiier.skin.intercept.RequestTaskIntercept;
import com.smiier.skin.ui.BasicActivity;
import com.smiier.skin.utils.CommonUtility;
import com.smiier.skin.utils.DBUtil;
import com.smiier.skin.vo.Keyword;
import com.umeng.analytics.MobclickAgent;

public class SearchQuestionActivity extends BasicActivity implements
		OnRefreshListener<ListView> {

	private EditText edit_search;
	private TextView text_right;
	ListView list_keywords;
	PullToRefreshListView list_questions;

	private LinearLayout ll_keywords;

	ArrayList<Keyword> keywords;
	KeywordsAdapter keywordsAdapter;

	HashMap<String, Object> params = new HashMap<String, Object>();
	QuestionAdapter adapter;
	int start_qid;
	ArrayList<Object> array = new ArrayList<Object>();
	DBUtil dbUtil;

	private TextView text_empty;
	private TextView mHeader;
	private static final String mHeadString = "以下是有关“%s”的问题";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_question);

		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
		params.put(Constant.PARAM_API, "Question.GetList");
		params.put("pageSize", Constant.pageSize);

		edit_search = (EditText) findViewById(R.id.edit_search);
		text_right = (TextView) findViewById(R.id.text_right);
		list_keywords = (ListView) findViewById(R.id.list_keywords);
		list_questions = (PullToRefreshListView) findViewById(R.id.list_questions);
		ll_keywords = (LinearLayout) findViewById(R.id.ll_keywords);
		text_empty = (TextView) findViewById(R.id.text_empty);
		list_questions.setOnRefreshListener(this);
		mHeader = new TextView(getContext());
		mHeader.setTextColor(getResources().getColor(R.color.text_gray));
		mHeader.setTextSize(12);
		mHeader.setPadding((int) OUtil.dp2px(getContext(), 12),
				(int) OUtil.dp2px(getContext(), 15), 0, 0);
		list_questions.setPullLoadEnabled(false);
		list_questions.setScrollLoadEnabled(true);
		list_questions.getListView().addHeaderView(mHeader);
		list_questions.hideDivider();

		dbUtil = DBUtil.getInstance(activity);
		keywords = dbUtil.query(Keyword.class, null, null, null, "id desc");
		keywordsAdapter = new KeywordsAdapter(activity, keywords);
		list_keywords.setAdapter(keywordsAdapter);
		edit_search.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence text, int arg1, int arg2,
					int arg3) {
				if (!CommonUtility.isNull(text)) {
					text_right.setText("搜索");
					list_questions.setVisibility(View.GONE);
					ll_keywords.setVisibility(View.VISIBLE);
				} else {
					text_right.setText("取消");
				}

				keywords = DBUtil.getInstance(activity)
						.query(Keyword.class, null, "keyword like ?",
								new String[] { "%" + text.toString() + "%" },
								"id desc");
				keywordsAdapter.notifyUpdate(keywords);
				mHeader.setText(String.format(mHeadString, text));
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {

			}

			@Override
			public void afterTextChanged(Editable arg0) {

			}
		});
		list_keywords.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int arg2, long arg3) {
				String keyword = (String) view.getTag();
				search(keyword);
			}
		});

		list_questions.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view,
					int arg2, long arg3) {
				JSONObject object = (JSONObject) view.getTag(R.id.tag_obj);
				Intent intent = new Intent(activity,
						QuestionDetailActivity.class);
				intent.putExtra(Constant.IDENTITY_KEY, object.toString());
				startActivity(intent);
			}
		});

		edit_search.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {

				if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED) {

					String keyword = edit_search.getText().toString();
					search(keyword);
					CommonUtility.hideKeyboard(activity, text_right);
				}

				return false;

			}
		});
	}

	public void onClick(View view) {
		int id = view.getId();
		if (id == R.id.text_right) {
			if (text_right.getText().toString().equals("取消")) {
				finish();
			} else {
				String keyword = edit_search.getText().toString();
				search(keyword);
				CommonUtility.hideKeyboard(activity, view);
			}
		}
	}

	void search(String keyword) {
		if (!CommonUtility.isNull(keyword)) {
			params.put("keyword", keyword);
			list_questions.setVisibility(View.VISIBLE);
			ll_keywords.setVisibility(View.GONE);
			int count = dbUtil.getCount(Keyword.class.getSimpleName(),
					"where keyword = ?", new String[] { keyword });
			if (count < 1) {
				ContentValues values = new ContentValues();
				values.put("keyword", keyword);
				dbUtil.insert(Keyword.class.getSimpleName(), values);
			}
			list_questions.doPullRefreshing(true);
			text_right.setText("取消");
		} else {
			CommonUtility.toast(activity, "请输入关键字");
		}
	}

	private void loadData() {
		params.put("statuses", 3);
		params.put("startQid", start_qid);
		RequestTaskIntercept.requestIntercept(activity, Constant.URL.REQUEST,
				new RequestHandler(activity, new HandlerCallback() {

					@Override
					public void callback(Object o) {
						list_questions.onPullDownRefreshComplete();
						list_questions.onPullUpRefreshComplete();
						list_questions.setLastUpdateTime();
						if (!CommonUtility.isNull(o)) {
							JSONObject object = (JSONObject) o;
							if (CommonUtility.response200(object)) {
								try {
									object = object.getJSONObject("Res");
									JSONArray arr = (JSONArray) object
											.getJSONArray("Questions");
									if (arr.length() > 0) {
										CommonUtility.putAll(array, arr, true);
										list_questions.setHasMoreData(true);
									} else {
										if (array.size() > 0) {
											list_questions
													.setHasMoreData(false);
										}
									}
									if (array.size() > 0) {
										start_qid = ((JSONObject) array
												.get(array.size() - 1))
												.getInt("Qid");
										text_empty.setVisibility(View.GONE);
									} else {
										text_empty.setVisibility(View.VISIBLE);
									}
									if (CommonUtility.isNull(adapter)) {
										adapter = new QuestionAdapter(activity,
												array);
										list_questions.setAdapter(adapter);
									} else {
										adapter.notifyUpdate();
									}
									if (array.size() < 1) {
										/*
										 * if (mHeader.getParent() != null) {
										 * list_questions.getListView()
										 * .removeView(mHeader); }
										 */
										list_questions.setContextEmptyType(
												true, 2);
									} else {
										/*
										 * if (mHeader.getParent() == null) {
										 * list_questions.getListView()
										 * .addHeaderView(mHeader); }
										 */
										list_questions.setContextEmptyType(
												false, 2);
									}
								} catch (Exception e) {
									e.printStackTrace();
								}
							} else {
								list_questions.setContextEmptyType(true, 2);
								CommonUtility.toast(activity,
										R.string.server_unavailable);
							}
						}
					}
				}), false, params);
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		start_qid = 0;
		array.clear();
		loadData();
	}

	@Override
	public void onPullUpToLoadMore(PullToRefreshBase<ListView> refreshView) {
		loadData();
	}

	public static class KeywordsAdapter extends BaseAdapter {

		private ArrayList<Keyword> items;

		View[] views;
		LayoutInflater inflater;

		public KeywordsAdapter(Context context, ArrayList<Keyword> items) {
			this.items = items;
			views = new View[items.size()];
			inflater = LayoutInflater.from(context);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			convertView = views[position];
			if (!CommonUtility.isNull(convertView)) {
				return convertView;
			}
			Keyword keyword = (Keyword) getItem(position);
			convertView = inflater.inflate(R.layout.item_keyword, null);
			TextView text_keyword = (TextView) convertView
					.findViewById(R.id.text_keyword);

			text_keyword.setText(keyword.keyword);
			convertView.setTag(keyword.keyword);
			return convertView;
		}

		@Override
		public int getCount() {
			return items.size();
		}

		@Override
		public Object getItem(int position) {
			return items.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		public void notifyUpdate(ArrayList<Keyword> keywords) {
			this.items = keywords;
			views = null;
			views = new View[items.size()];
			notifyDataSetChanged();
		}

	}
	
	
	
/*	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onResume(getContext());
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPause(getContext());
	}*/

}
